/**
 * Copyright 2015 jianglibo@gmail.com
 *
 */
package com.m3958.logcollector.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.auditing.AuditableBeanWrapperFactory;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.repository.support.RepositoryInvoker;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.event.AfterCreateEvent;
import org.springframework.data.rest.core.event.BeforeCreateEvent;
import org.springframework.data.rest.core.mapping.ResourceType;
import org.springframework.data.rest.webmvc.ControllerUtils;
import org.springframework.data.rest.webmvc.PersistentEntityResource;
import org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.data.rest.webmvc.RootResourceInformation;
import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.m3958.logcollector.datacommons.controller.AbstractQcontroller;
import com.m3958.logcollector.domain.Person;
import com.m3958.logcollector.repository.PersonRepository;
import com.m3958.logcollector.userdetail.PersonManager;
import com.m3958.logcollector.vo.PersonVo;

/**
 * @author jianglibo@gmail.com
 *         2015年12月24日
 *
 */
@RepositoryRestController
public class PeopleController extends AbstractQcontroller implements ApplicationEventPublisherAware {
    
    protected final RepositoryEntityLinks entityLinks;
	
	@Autowired
	private PersonManager personManager;
	
	@Autowired
	private static PersonRepository personReop;
    
    @Autowired
    public PeopleController(Repositories repositories, RepositoryRestConfiguration config, RepositoryEntityLinks entityLinks,
            PagedResourcesAssembler<Object> assembler, @Qualifier("defaultConversionService") ConversionService conversionService,
            AuditableBeanWrapperFactory auditableBeanWrapperFactory) {
        super(assembler, auditableBeanWrapperFactory, entityLinks, config);
        this.entityLinks = entityLinks;
    }
    
	@ResponseBody
	@RequestMapping(value = "/people", method = RequestMethod.POST)
	public ResponseEntity<ResourceSupport> postCollectionResource(RootResourceInformation resourceInformation,
			PersistentEntityResource payload, PersistentEntityResourceAssembler assembler,
			@RequestHeader(value = ACCEPT_HEADER, required = false) String acceptHeader)
					throws HttpRequestMethodNotSupportedException {

		resourceInformation.verifySupportedMethod(HttpMethod.POST, ResourceType.COLLECTION);

		return createAndReturn(payload.getContent(), resourceInformation.getInvoker(), assembler,
				getConfig().returnBodyOnCreate(acceptHeader));
	}
	
	
    protected ResponseEntity<ResourceSupport> createAndReturn(Object domainObject, RepositoryInvoker invoker, PersistentEntityResourceAssembler assembler,
            boolean returnBody) {

        getPublisher().publishEvent(new BeforeCreateEvent(domainObject));
        
//        Object savedObject = invoker.invokeSave(domainObject);
	    Person personBeforeSave = (Person) domainObject;
        personManager.createUser(new PersonVo((Person) domainObject));
        Person savedObject = personReop.findByEmail(personBeforeSave.getEmail());
        
        getPublisher().publishEvent(new AfterCreateEvent(savedObject));

        PersistentEntityResource resource = returnBody ? assembler.toFullResource(savedObject) : null;

        HttpHeaders headers = prepareHeaders(resource);
        addLocationHeader(headers, assembler, savedObject);

        return ControllerUtils.toResponseEntity(HttpStatus.CREATED, headers, resource);
    }

}
